<template>
  <el-dialog v-model="showVisible" title="导出" width="500" @close="closeDialog">
    <el-form v-loading="pageLoading" label-width="auto" style="max-width: 600px">
      <el-form-item label="导出方式:">
        <el-radio-group v-model="exportType">
          <el-radio :value="1" size="large">按模板</el-radio>
          <el-radio :value="2" size="large">按负责人</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="exportType === 1" label="任务名:">
        <!--        <el-select v-model="selectValue" placeholder="Select" size="large">-->
        <!--          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />-->
        <!--        </el-select>-->
        <el-select popper-class="select-user-popper" v-model="selectValue" placeholder="请选择" @change="changeUser">
          <template #header>
            <div class="content-item-search">
              <el-input placeholder="请输入关键词" v-model="keyWords" @change="handelSearchUser(index)" />
              <svg-icon iconClass="searchBox-icon" style="font-size: 24px" @click="handelSearchUser(index)" />
            </div>
          </template>
          <el-option
            v-for="userItem in options"
            :key="userItem.uuid"
            :v-loading="loading"
            :label="userItem.type"
            :value="userItem.uuid"
          >
            <!--            <template #default>-->
            <!--              <div class="content-item-option">-->
            <!--                <span>{{ type[userItem.type] }}</span>-->
            <!--                <span>{{ userItem.userName }}</span>-->
            <!--              </div>-->
            <!--            </template>-->
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="exportType === 2" label="负责人:">
        <el-select
          popper-class="select-user-popper"
          clearable
          v-model="userId"
          placeholder="请选择"
          @clear="clearAssignBlameUser"
          @change="changeAssignBlameUser"
        >
          <template #header>
            <div class="content-item-search">
              <el-input placeholder="请输入关键词" v-model="userKeyword" @change="searchAssignBlameUser" />
              <svg-icon iconClass="searchBox-icon" style="font-size: 24px" @click="searchAssignBlameUser" />
            </div>
          </template>
          <el-option
            v-for="userItem in assignBlameUsers"
            :key="userItem.userId"
            :v-loading="assignBlameLoading"
            :label="userItem.nickName"
            :value="userItem.userId"
          >
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="showVisible = false">取消</el-button>
        <el-button type="primary" @click="onConfirm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { computed, ref, getCurrentInstance } from "vue";
import { exportTaskDataSearch, exportTaskList } from "@/apis/myClient";
import { generateId } from "@/utils/crm";
import { dayjs } from "element-plus";
import { documentFlow } from "@/utils/downFile";
import requestApis from "@/views/taskManager/apis";

let props = defineProps(["modelValue", "tableParams", "daterange"]);
let $emit = defineEmits(["update:modelValue", "handleExportData"]);
const { proxy } = getCurrentInstance();

//过滤分页信息
const exportFilterCondition = ref(props.tableParams);
if (exportFilterCondition.value.hasOwnProperty("current")) {
  delete exportFilterCondition.value.current;
}
if (exportFilterCondition.value.hasOwnProperty("size")) {
  delete exportFilterCondition.value.size;
}
exportFilterCondition.value.startDate = props.daterange?.length >= 2 ? props.daterange[0] : "";
exportFilterCondition.value.endDate = props.daterange?.length >= 2 ? props.daterange[1] : "";

// console.log("导出参数", exportFilterCondition.value);

const showVisible = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    $emit("update:modelValue", val);
  }
});

const onConfirm = async () => {
  if (exportType.value === 1 && !paramsData.value.taskName) {
    return proxy.$modal.msgError("请选择任务");
  }
  if (exportType.value === 2 && !userId.value) {
    return proxy.$modal.msgError("请选择负责人");
  }
  try {
    pageLoading.value = true;
    const res = await exportTaskList({
      exportType: exportType.value,
      ...exportFilterCondition.value,
      ...paramsData.value
    });
    pageLoading.value = false;
    const time = dayjs().format("YYYYMMDDHHmmss");
    const fileName = exportType.value === 1 ? `${currentExportName.value}-${time}` : `${paramsData.value.userName}-${time}`;
    documentFlow(res, fileName, "xlsx");
    // proxy.$modal.msgSuccess("保存成功");
    showVisible.value = false;
  } catch (err) {
    pageLoading.value = false;
  }
};
const closeDialog = () => {
  showVisible.value = false;
};

const loading = ref(false);
const pageLoading = ref(false);
const selectValue = ref("");
const currentExportName = ref("");
const paramsData = ref({ taskName: "", taskNodeType: "", busType: "", userName: "" });
const keyWords = ref("");
const exportType = ref(1);
const options = ref([]);
const changeUser = e => {
  const filterObj = options.value.find(item => item.uuid === e);
  if (filterObj) {
    paramsData.value.taskName = filterObj.taskName;
    paramsData.value.taskNodeType = filterObj.taskNodeType;
    paramsData.value.busType = filterObj.busType;
    currentExportName.value = filterObj.type;
  }
};
const handelSearchUser = async index => {
  if (!keyWords.value) return;
  try {
    loading.value = true;
    const { data } = await exportTaskDataSearch({ keywords: keyWords.value });
    options.value = data ?? [];
    if (options.value.length > 0) {
      options.value.map(item => {
        item.uuid = generateId();
      });
    }
    loading.value = false;
  } catch (err) {
    loading.value = false;
  }
};

/**
 * 责任人搜索
 */
const assignBlameLoading = ref(false);
const assignBlameUsers = ref([]);
const userId = ref("");
const userKeyword = ref("");
const searchAssignBlameUser = async e => {
  if (!userKeyword.value) return;
  try {
    assignBlameLoading.value = true;
    const { data } = await requestApis.searchUser({ name: userKeyword.value });
    assignBlameUsers.value = data ?? [];
    assignBlameLoading.value = false;
  } catch (err) {
    assignBlameLoading.value = false;
  }
};
const changeAssignBlameUser = e => {
  const userInfo = assignBlameUsers.value.find(item => item.userId === e);
  userInfo && (paramsData.value.userName = userInfo.nickName);
};
const clearAssignBlameUser = () => {
  paramsData.value.userName = "";
};
</script>

<style scoped lang="scss">
@use "@/assets/styles/mixin";
.select-user-popper {
  border: 1px solid #0052d9 !important;
  box-shadow: 0 0 0 2px #d9e1ff !important;
  border-radius: 3px;
  .el-select-dropdown__header {
    padding: 10px 5px 4px 5px !important;
  }
  .el-scrollbar__view > .el-select-dropdown__item {
    @include mixin.flex-align;
    padding-left: 10px;
    padding-right: 10px;
    //font-size: 12px;
    color: #3d3d3d;
    line-height: 22px;
  }
  .el-popper__arrow::before {
    display: none;
  }
}
.content-item-search {
  @include mixin.flex-align;
  :deep(.el-input__wrapper) {
    border: 0;
    box-shadow: none;
    outline: 0;
    &:hover {
      box-shadow: none;
    }
    &.is-focus {
      box-shadow: none;
    }
  }
  :deep(.svg-icon) {
    margin-right: 5px;
    cursor: pointer;
  }
}
.content-item-option {
  @include mixin.flex-center(space-between, center);
  width: 100%;
}

.dialog-footer {
  text-align: center;
}
</style>
